<?php

namespace Views;
use App;
use Document;

/**
 * @author Evgeny Baranov <evgeny@baranov.eu>
 */
abstract class Base {

    /**
     * @var \DOMDocumentFragment
     */
    protected $fragment;

    /**
     * @var string
     */
    protected $tmpl;

    /**
     * @var array
     */
    protected $data = array();

    /**
     * @var string
     */
    protected $block = 'Main';

    public function __construct() {
    }

    /**
     * @return \DOMDocumentFragment
     */
    public function render() {
        ob_start();
        $this->includeTemplate();
        $data = ob_get_clean();
        $this->fragment = App::getDocument()->createDocumentFragment();
        $this->fragment->validateOnParse = false;
        $this->fragment->appendXML($data);
        return $this->fragment;
    }

    /**
     * @param string $key
     * @param mixed $val
     * @return \Views\Base
     */
    public function setData($key, $val) {
        $this->data[$key] = $val;
        return $this;
    }

    /**
     * @param $key
     * @return mixed
     */
    public function getData($key) {
        return $this->data[$key];
    }

    /**
     * @param string $tmpl
     * @return \Views\Base
     */
    public function setTemplate($tmpl) {
        $this->tmpl = $tmpl;
        return $this;
    }

    /**
     * @return string
     */
    public function getTemplate() {
        return $this->tmpl;
    }

    protected function includeTemplate() {
        $t = TMPL_DIR . DS . str_replace(NS, DS, \get_called_class()) . DS . $this->getTemplate();
        require $t;
    }

    /**
     * @param string|array $href
     * @param string $media
     * @return Document
     */
    public function addCSSLink($href, $media = 'all') {
        App::getDocument()->addCSSLink($href, $media);
        return $this;
    }

    /**
     * @param string $src
     * @param string $text
     * @return Document
     */
    public function addScript($src, $text = '') {
        App::getDocument()->addScript($src, $text);
        return $this;
    }

    protected function T($key, $block = null) {
        if (!$block) {
            $block = $this->block;
        }
        return _t($key, $block);
    }
}